package com.kyomonn.talkischeap.DeepSeek;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.kyomonn.talkischeap.R;

import java.util.ArrayList;
import java.util.List;

public class DeepSeekFragment extends Fragment {
    private static DeepSeekViewModel viewModelInstance;
    private EditText etInput;
    private RecyclerView rvChat;
    private ChatAdapter chatAdapter;
    private List<Message> messageList;

    public static DeepSeekViewModel getDeepSeekViewModel(Fragment fragment) {
        if (viewModelInstance == null) {
            viewModelInstance = new ViewModelProvider(fragment.requireActivity()).get(DeepSeekViewModel.class);
        }
        return viewModelInstance;
    }

    public static DeepSeekFragment Create() {
        return new DeepSeekFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_deep_seek, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModelInstance = new ViewModelProvider(requireActivity()).get(DeepSeekViewModel.class);

        etInput = view.findViewById(R.id.et_input);
        Button btnSend = view.findViewById(R.id.btn_send);
        rvChat = view.findViewById(R.id.rv_chat);

        messageList = new ArrayList<>();
        chatAdapter = new ChatAdapter(messageList);
        rvChat.setLayoutManager(new LinearLayoutManager(getContext()));
        rvChat.setAdapter(chatAdapter);

        btnSend.setOnClickListener(v -> {
            String input = etInput.getText().toString().trim();
            if (!input.isEmpty()) {
                // 添加用户消息
                messageList.add(new Message(input, true));
                chatAdapter.notifyItemInserted(messageList.size() - 1);
                etInput.setText("");

                // AI 回复
                messageList.add(new Message("正在思考...", false));
                new android.os.Handler().postDelayed(() -> {
                    messageList.get(messageList.size() - 1).setContent("");
                }, 1000);
                DeepSeekClient.sendMessageReplyStream(input, new StreamCallback() {
                    private final StringBuilder fullResponse = new StringBuilder();

                    @Override
                    public void onTokenReceived(String data) {
                        requireActivity().runOnUiThread(() -> {
                            fullResponse.append(data); // 累积数据块
                            messageList.get(messageList.size() - 1).setContent(fullResponse.toString()); // 最后一条消息就是AI的回复
                            chatAdapter.notifyItemChanged(messageList.size() - 1); // 刷新适配器
                        });
                    }

                    @Override
                    public void onCompleted() {
                        requireActivity().runOnUiThread(() -> {
                            rvChat.scrollToPosition(messageList.size() - 1); // 滚动到底部
                            Log.d("MyTag", "流式数据接收完成");
                        });
                    }

                    @Override
                    public void onError(Exception e) {
                        requireActivity().runOnUiThread(() -> {
                            Log.e("MyTag", "发生错误: " + e.getMessage());
                            messageList.add(new Message("错误: " + e.getMessage(), false)); // 添加错误信息
                            chatAdapter.notifyItemInserted(messageList.size() - 1);
                        });
                    }
                });
            }
        });
    }
}